<template>
  <ToolBox title="位置记录" @close="handleClose" :show="show" :width="480">
    <el-form size="small">
      <el-form-item label="事件类型">
        <el-radio-group v-model="selectedCaseValue" @change="handleCaseChange">
          <el-radio-button
            v-for="caseItem in RecordStatics"
            :label="caseItem.label"
            :value="caseItem.value"
          />
        </el-radio-group>
      </el-form-item>
      <!-- <el-divider /> -->
      <el-form-item label="影响程度">
        <el-radio-group
          v-model="selectedIntensityValue"
          v-if="selectedCase.selectType == 'radio'"
        >
          <el-radio-button
            v-for="intensityItem in selectedCase.intensity"
            :label="intensityItem.label"
            :value="intensityItem.value"
          />
        </el-radio-group>
        <el-select
          v-model="selectedIntensityValue"
          v-else-if="selectedCase.selectType == 'select'"
        >
          <el-option
            v-for="intensityItem in selectedCase.intensity"
            :label="intensityItem.label"
            :value="intensityItem.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="高度范围">
        <div class="w100">
          <el-slider
            v-model="altitudeRange"
            range
            show-stops
            :min="1200"
            :max="7200"
            :step="300"
          />
        </div>
        <div class="altimiter w100">
          <span>{{ altitudeRange[0] }}m</span>
          <span>{{ altitudeRange[1] }}m</span>
        </div>
      </el-form-item>
      <el-form-item label="事件时间">
        <el-date-picker
          v-model="eventDate"
          type="date"
          placeholder="日期"
          style="width: 120px"
        />

        <el-time-picker
          v-model="eventTime"
          placeholder="时间"
          style="width: 100px; margin-left: 12px"
        />
      </el-form-item>
      <!-- <el-divider /> -->
      <el-form-item label="席位信息">
        <el-tag class="tag">{{ seatIP }}</el-tag>
        <el-tag class="tag">{{ seatName }}</el-tag>
        <el-tag class="tag">{{ seatUserName }}</el-tag>
        <el-tag class="tag">{{ `(${coordinate.x},${coordinate.y})` }}</el-tag>
      </el-form-item>
      <el-divider />
    </el-form>
    <div style="width: 100%; text-align: center">
      <el-button type="primary" @click="handleSubmit">
        <el-icon><Upload /></el-icon>
        <span>提交</span>
      </el-button>
      <el-button @click="handleClose" link>取消</el-button>
    </div>
  </ToolBox>
</template>

<script setup>
import { ref, computed, nextTick, onMounted } from "vue";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
import axios from "axios";
import dayjs from "dayjs";
import RecordStatics from "./RecordStatics.json";
import useSeatStore from "@/store/seat.js";
import ToolBox from "@/components/ToolBoxWindow/index.vue";

const show = ref(false);
const coordinate = ref();
const mousePosition = ref({ x: 0, y: 0 });
const gridId = ref();

const open = async (payload) => {
  // open the toolbox window with the provided coordinate
  show.value = false;
  coordinate.value = payload.coordinate;
  mousePosition.value = payload.mousePosition;
  gridId.value = payload.gridId;
  eventTime.value = new Date();
  eventDate.value = new Date();
  await nextTick();
  show.value = true;
};
defineExpose({ open });

const selectedCaseValue = ref("TUB");
const selectedCase = computed(() => {
  let itemList = RecordStatics.filter(
    (item) => item.value == selectedCaseValue.value
  );
  if (itemList) {
    return itemList[0];
  } else {
    return null;
  }
});

const selectedIntensityValue = ref(1);
const selectedIntensity = computed(() => {
  if (!selectedCase.value) {
    return null;
  }
  let itemList = selectedCase.value.intensity.filter(
    (item) => item.value == selectedIntensityValue.value
  );
  if (itemList) {
    return sitemList[0];
  } else {
    return null;
  }
});

const handleCaseChange = () => {
  selectedIntensityValue.value = 1;
};

const altitudeRange = ref([3600, 4800]);

const eventDate = ref(new Date());

const eventTime = ref(new Date());

const seatStore = useSeatStore();

const seatIP = computed(() => seatStore.currentSeat.ip);

const seatName = computed(() => seatStore.currentSeat.seatName);

const seatUserName = computed(() => {
  let seatContent = seatStore.seatStatus.filter(
    (seat) => seat.seatName == seatStore.currentSeat.seatName
  );
  if (seatContent.length > 0) {
    let userContent = seatContent[0].users.filter(
      (user) => user.seatPostId == 2 && user.seatRoleId != 3
    );
    if (userContent.length > 0) {
      return userContent[0].userName;
    }
  }
  return "未知人员";
});

const handleClose = () => {
  show.value = false;
};

const handleSubmit = () => {
  // validate the form inputs before submitting the payload
  const submitPayload = {
    method: "SAVE",
    case: selectedCaseValue.value,
    intensity: selectedIntensityValue.value,
    levelBottom: altitudeRange.value[0],
    levelTop: altitudeRange.value[1],
    eventTime:
      dayjs(eventDate.value).format("YYYY-MM-DD") +
      " " +
      dayjs(eventTime.value).format("HH:mm:ss"),
    x: coordinate.value.x,
    y: coordinate.value.y,
    // altitudeRange: altitudeRange.value,
    // eventDate: eventDate.value,
    // eventTime: eventTime.value,
    // coordinate: coordinate.value,
    // gridId: gridId.value,
    seatIP: seatIP.value,
    seatName: seatName.value,
    seatUserName: seatUserName.value,
  };
  // TODO: send the payload to the server for recording the event
  axios
    .post("api/journal_position_record.php", submitPayload)
    .then((response) => {
      if (response.data.success) {
        console.log("事件记录成功", submitPayload, response.data);
        ElNotification({
          title: "已完成",
          // message: JSON.stringify(submitPayload, null, 2),
          type: "success",
        });
        handleClose();
      } else {
        ElNotification({
          title: "失败了！",
          // message: "事件记录失败",
          type: "warning",
        });
      }
    })
    .catch((error) => {
      console.error("记录失败", error);
      ElNotification({
        title: "记录失败",
        message: error.message,
        type: "error",
      });
    });
};

onMounted(() => {
  axios
    .get("api/journal_position_record.php?method=GET_LAST_SUBMIT")
    .then((response) => {
      const lastSubmit = response.data.result;
      if (lastSubmit) {
        selectedCaseValue.value = lastSubmit.case;
        selectedIntensityValue.value = lastSubmit.intensity;
        altitudeRange.value = [lastSubmit.levelBottom, lastSubmit.levelTop];
        ElMessage({ type: "info", message: "已载入最近一次提交数据" });
      }
    });
});
</script>

<style scoped>
.w100 {
  width: 100%;
}
.altimiter {
  display: flex;
  justify-content: space-between;
  color: var(--el-text-color-secondary);
}

.header {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 1.25em;
  font-weight: bold;
}

.tag {
  margin-right: 8px;
}
</style>
